import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple
from decimal import Decimal

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历_获取招聘信息的来源分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None,
    education: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历，获取招聘信息的来源分布 - 指标计算函数
    
    ## 指标说明
    计算各学历层次学生获取招聘信息不同来源的占比分布情况。指标基于问卷问题T00003298的答案数据，
    统计每个选项被选择的比例，并按学历分组展示结果。同时包含总体数据汇总。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        education (Optional[str]): 学历筛选条件，可选值:本科毕业生/专科毕业生/硕士研究生/博士研究生
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": [
            {
                "group": "总体",
                "data": [
                    {"source": "校园招聘会或学校发布的招聘信息", "ratio": 0.45},
                    {"source": "学校老师推荐", "ratio": 0.15},
                    {"source": "工作实习", "ratio": 0.10},
                    {"source": "校外招聘会", "ratio": 0.08},
                    {"source": "校外各类招聘网站信息", "ratio": 0.12},
                    {"source": "家庭或其他社会关系", "ratio": 0.07},
                    {"source": "其他", "ratio": 0.03}
                ]
            },
            {
                "group": "博士研究生",
                "data": [
                    {"source": "校园招聘会或学校发布的招聘信息", "ratio": 0.50},
                    {"source": "学校老师推荐", "ratio": 0.20},
                    {"source": "工作实习", "ratio": 0.05},
                    {"source": "校外招聘会", "ratio": 0.05},
                    {"source": "校外各类招聘网站信息", "ratio": 0.10},
                    {"source": "家庭或其他社会关系", "ratio": 0.05},
                    {"source": "其他", "ratio": 0.05}
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历，获取招聘信息的来源分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year, dy_target_items, split_tb_paper 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        split_tb_paper = project_info['split_tb_paper']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}, split_tb_paper={split_tb_paper}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 查询问卷信息
        questionnaire_sql = f"""
        SELECT id, dy_target 
        FROM wt_template_customer 
        WHERE id IN ({','.join(['%s'] * len(questionnaire_ids))})
        """
        questionnaires = db.fetchall(questionnaire_sql, tuple(questionnaire_ids))
        if not questionnaires:
            raise ValueError(f"未找到问卷ID集合={questionnaire_ids}的配置信息")
        
        logger.info(f"查询到问卷信息: {questionnaires}")

        # 4. 过滤GRADUATE_SHORT调研对象的问卷
        valid_questionnaire_ids = [q['id'] for q in questionnaires if q['dy_target'] == 'GRADUATE_SHORT']
        if not valid_questionnaire_ids:
            raise ValueError("未找到GRADUATE_SHORT调研对象的问卷ID")
            
        logger.info(f"找到有效问卷ID: {valid_questionnaire_ids}")

        # 5. 查询问题信息
        question_sql = """
        SELECT id, wt_code, wt_obj 
        FROM wt_template_question_customer 
        WHERE cd_template_id = %s AND wt_code = 'T00003298' AND is_del = 0
        """
        question_info = db.fetchone(question_sql, (valid_questionnaire_ids[0],))
        if not question_info:
            raise ValueError("未找到问题编码T00003298的问题信息")
            
        logger.info(f"找到问题信息: {question_info['id']}")

        # 6. 解析问题选项
        wt_obj = json.loads(question_info['wt_obj'])
        options = []
        for item in wt_obj['itemList']:
            options.append({
                'key': item['key'],
                'val': item['val']
            })

        # 7. 构建动态表名
        answer_table = f"re_dy_paper_answer_{split_tb_paper}"
        student_table = f"dim_client_target_baseinfo_student_{item_year}"

        # 8. 定义学历分组
        education_groups = ['本科毕业生', '专科毕业生', '硕士研究生', '博士研究生']
        if education:
            education_groups = [education]
            
        # 9. 计算各学历分组数据
        result = []
        
        # 9.1 计算总体数据
        total_sql = f"""
        SELECT
            SUM(c1) as c1,
            SUM(c2) as c2,
            SUM(c3) as c3,
            SUM(c4) as c4,
            SUM(c5) as c5,
            SUM(c6) as c6,
            SUM(c7) as c7
        FROM {answer_table} t1
        JOIN {student_table} s ON t1.target_no = s.target_no
        WHERE
            t1.cd_template_id = %s
            AND t1.wid = %s
            AND t1.ans_true = 1
            AND s.shard_tb_key = %s
            AND s.item_year = %s
        """
        total_params = (valid_questionnaire_ids[0], question_info['id'], shard_tb_key, item_year)
        total_result = db.fetchone(total_sql, total_params)
        
        if not total_result:
            raise ValueError("未找到有效的答案数据")
        
        total_counts = [float(total_result[f'c{i}'] or 0) for i in range(1, 8)]
        total_sum = sum(total_counts) or 1  # 避免除以0
        
        total_data = []
        for idx, opt in enumerate(options):
            total_data.append({
                "source": opt['val'],
                "ratio": round(total_counts[idx]/total_sum, 4)
            })
        
        result.append({
            "group": "总体",
            "data": total_data
        })

        # 9.2 计算各学历分组数据
        for edu in education_groups:
            edu_sql = f"""
            SELECT
                SUM(c1) as c1,
                SUM(c2) as c2,
                SUM(c3) as c3,
                SUM(c4) as c4,
                SUM(c5) as c5,
                SUM(c6) as c6,
                SUM(c7) as c7
            FROM {answer_table} t1
            JOIN {student_table} s ON t1.target_no = s.target_no
            WHERE
                t1.cd_template_id = %s
                AND t1.wid = %s
                AND t1.ans_true = 1
                AND s.shard_tb_key = %s
                AND s.item_year = %s
                AND s.education = %s
            """
            edu_params = (valid_questionnaire_ids[0], question_info['id'], shard_tb_key, item_year, edu)
            edu_result = db.fetchone(edu_sql, edu_params)
            
            if not edu_result:
                logger.warning(f"未找到{edu}学历的答案数据")
                continue
                
            edu_counts = [float(edu_result[f'c{i}'] or 0) for i in range(1, 8)]
            edu_sum = sum(edu_counts) or 1  # 避免除以0
            
            edu_data = []
            for idx, opt in enumerate(options):
                edu_data.append({
                    "source": opt['val'],
                    "ratio": round(edu_counts[idx]/edu_sum, 4)
                })
            
            result.append({
                "group": edu,
                "data": edu_data
            })

        logger.info(f"指标 '各学历，获取招聘信息的来源分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历，获取招聘信息的来源分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历，获取招聘信息的来源分布",
            "code": 500,
            "error": str(e)
        }